package com.dd.duu.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.dc.base.domain.DPage;
import com.dd.dc.base.domain.DResult;
import com.dd.dc.entity.users.DPermission;
import com.dd.dc.entity.users.DRole;
import com.dd.dc.entity.users.DRolePermissionRelation;
import com.dd.duu.service.RoleClient;
import com.dd.duu.vo.AuthorityTreeVo;
import feign.Param;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 角色信息表 前端控制器
 * </p>
 *
 * @author JueDream
 * @since 2021-03-05
 */
@Slf4j
@RestController
@RequestMapping("/role/c")
@GlobalTransactional(rollbackFor = Exception.class) // 分布式事务seata
public class RoleController {

    @Autowired
    RoleClient roleClient;

    @ApiOperation(value = "角色分页列表接口")
    @PostMapping("/queryRoleList")
    public DResult<DPage<DRole>> queryRoleList(@RequestParam int page, @RequestParam int limit, @RequestParam String roleName){
        log.info("UserUI queryRoleList start ... {}");
        Page<DRole> pages = roleClient.queryRoleList(page, limit, roleName);
        DPage<DRole> rolePage = DPage.to(pages);
        return DResult.of(rolePage);
    }

    @ApiOperation(value = "根据用户查询角色接口")
    @PostMapping("/findRoleByUserId")
    public DResult<List<DRole>> findRoleByUserId(@RequestBody Map<String,Object> map){
        log.info("UserUI findRoleByUserId start ... {}", map);
        Object userId = Optional.ofNullable(map.get("userId")).orElse(0);
        return DResult.of(roleClient.findRoleByUserId(Integer.parseInt(userId.toString())));
    }

    @ApiOperation(value = "根据用户查询角色接口-返回对比")
    @PostMapping("/findUserRoleByUserId")
    public DResult<AuthorityTreeVo> findUserRoleByUserId(@RequestBody Map<String,Object> map){
        log.info("UserUI findUserRoleByUserId start ... {}", map);
        Integer userId = 0;
        String userIdStr = map.get("userId").toString();
        if (StrUtil.isNotBlank(userIdStr)) {
            userId = Integer.parseInt(userIdStr);
        }
        List<DRole> roleAll = roleClient.findRoleByUserId(0);
        List<DRole> roleHave = roleClient.findRoleByUserId(userId);
        AuthorityTreeVo authorityTreeVo = AuthorityTreeVo.builder().roleAll(roleAll).roleHave(roleHave).build();
        return DResult.of(authorityTreeVo);
    }

    @Transactional
    @ApiOperation(value = "角色新增/更新")
    @PostMapping("saveOrUpdate")
    public DResult saveOrUpdate(@RequestBody DRole role){
        boolean flag = true;
        // 判断新增/更新
        if (Objects.isNull(role.getRoleId())) {
            // 新增角色
            roleClient.insert(role);
        }else{
            // 更新角色
            roleClient.updateById(role);
            // 删除角色权限关系
            roleClient.deleteRP(role.getRoleId());
        }
        // 新增/角色权限关系
        List<DPermission> permissions = role.getPermissions();
        List<DRolePermissionRelation> relations = new ArrayList<>();
        if (permissions.size() > 0) {
            permissions.forEach(p -> {
                DRolePermissionRelation relation = new DRolePermissionRelation();
                relation.setRoleId(role.getRoleId());
                relation.setPId(p.getPId());
                relations.add(relation);
            });
            flag = roleClient.saveBatchRP(relations);
        }
        return DResult.of(flag);
    }

    @Transactional
    @ApiOperation(value = "角色删除")
    @DeleteMapping("deleteRole")
    public DResult deleteRole(@RequestParam Integer roleId){
        // 验证当前角色是否还有绑定关系
        boolean flag = true;
        flag = roleClient.queryRelationByRoleId(roleId);
        if (flag) {
            flag = roleClient.delete(roleId);
        }
        return DResult.of(flag);
    }

}
